const config = {
	handshakeCommand: 'hello.redduck.chat.',
	open(server) {
		console.log('OPEN')
		document.getElementById('serverId').value = server.id
	},
	newUser(server, username) {
		console.log('NEWUSER', username)
	},
	deleteUser(server, username) {
		console.log('DELETEUSER', username)
	},
	data(server, username, data) {
		console.log('DATA', username, data)
		if (data.type === 'message') {
			addMessage(data.content)

			server.getUserList().forEach(function (username2) {
				if (username != username2)
					server.send(username2, data)
			})
		}
	},
}
let server = undefined
document.getElementById('create').addEventListener('click', function () {
	if (server) {
		toast('RedDuck server is already running!', 'info')
	} else {
		let serverId = document.getElementById('serverId').value
		if (!serverId)
			serverId = undefined
		server = createRedDuckServer(config, serverId)
	}
})
document.getElementById('close').addEventListener('click', function () {
	if (server) {
		server.close()
		server = undefined
	} else {
		toast('No RedDuck server is running!', 'info')
	}
})
document.getElementById('send').addEventListener('click', function () {
	if (server) {
		let messageText = document.getElementById('message').value
		document.getElementById('message').value = ''
		let message = { sender: 'server', date: new Date(), text: messageText }
		addMessage(message)

		server.getUserList().forEach(function (username) {
			server.send(username, { type: 'message', content: message })
		})
	} else {
		toast('No RedDuck server is running!', 'info')
	}
})